require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIRevengeRecord = {}
HelperFunc.SetUIEnv(UIRevengeRecord)
local this = UIRevengeRecord

function UIRevengeRecord.Init(data, closeFunc) 
    this.cur_type = data or 1
    local _name, _package = getUIName(PanelNames.UIRevengeRecord)
    panelMgr:ShowUI(_name, _package, this.onCreate, Config.useLocalUI)
end

function UIRevengeRecord.onCreate(obj) 
    if not this.hasInit then
        this.hasInit = true 
        this.btn_back = obj:GetChild("Btn_BgClose")
        this.btn_bg_back = obj:GetChild("Btn_BackButton")

        this.list_show = obj:GetController("list_show")

        this.list_rob = obj:GetChild("List_RobRecord") 
        this.list_rob.itemRenderer = this.UpdateRobItemRender

        this.list_revenge = obj:GetChild("List_RevengeRecord") 
        this.list_revenge.itemRenderer = this.UpdateRevengeItemRender

        this.list_rob:SetVirtual()
        this.list_revenge:SetVirtual()
        
        this.page_controller = obj:GetController("page")
        this.btn_rob_list = obj:GetChild("Btn_RobList")
        this.btn_revenge_list = obj:GetChild("Btn_RevengeList")
        this.addEvent()
    end 
    this.initData()
end
 
function UIRevengeRecord.initData()   
    this.rob_record_over_time = dataTable.getDataTableByStringId("t_global", 336 ,"f_int_value") 
    this.item_rewards = nil
    this.sub_items = {}
    this.rob_history_list = {}
    this.revenge_history_list = {}
    this.timer_list = {}
    this.list_revenge.numItems = 0
    this.list_show:SetSelectedIndex(1) 
    if this.cur_type == 1 then
        this.page_controller:SetSelectedIndex(0)
        plunderHandler.sendReqRobList( 1 ) -- 掠夺记录
    else
        plunderHandler.SetRevengeListRedDotData( false )
        this.page_controller:SetSelectedIndex(1)
        plunderHandler.sendReqRobList( 2 ) --复仇记录 
    end
    
end

function UIRevengeRecord.RefreshRobRecordList()
    if this.rob_history_list ~= nil and next(this.rob_history_list) ~= nil then
        table.sort(this.rob_history_list, function(a, b)
            if a.type == 3 and b.type == 3 then 
                local a_dis_time = tonumber(tostring(a.record.createTime)) + this.rob_record_over_time - Config.serverTime
                local b_dis_time = tonumber(tostring(b.record.createTime)) + this.rob_record_over_time - Config.serverTime 
                if a_dis_time > 0 and b_dis_time > 0 then
                    return a_dis_time < b_dis_time
                elseif a_dis_time > 0 and b_dis_time <= 0 then
                    return false
                elseif a_dis_time <= 0 and b_dis_time > 0 then
                    return true
                else
                    return a_dis_time > b_dis_time
                end
            elseif a.type == 3 and b.type ~= 3 then
                return true
            elseif a.type ~= 3 and b.type == 3 then
                return false
            else
                return tonumber(tostring(a.record.createTime)) > tonumber(tostring(b.record.createTime))
            end 
        end)
    end
    if #this.rob_history_list > 0 then
        this.list_show:SetSelectedIndex(0)
    else
        this.list_show:SetSelectedIndex(1)
    end
    this.list_rob.numItems = #this.rob_history_list 
end
function UIRevengeRecord.ResUpdateRobRecordInfo( msg )
       
    this.ClearTimer()
    this.sub_items = {}
    if this.cur_type == 1 then
        this.rob_history_list = {}
        if msg and msg.type == 1 and  msg.list and next(msg.list) ~= nil then 
            for _, v in pairs(msg.list) do
                table.insert(this.rob_history_list, v)
            end
            this.RefreshRobRecordList()
        else
            this.list_rob.numItems = 0
            this.list_show:SetSelectedIndex(1)
        end
    else
        this.revenge_history_list = {}
        if msg and msg.type == 2 and msg.list and next(msg.list) ~= nil then 
            for _, v in pairs(msg.list) do
                table.insert(this.revenge_history_list, v)
            end
            this.RefreshRevengeRecordList()
        else
            this.list_revenge.numItems = 0
            this.list_show:SetSelectedIndex(1)
        end
    end  
end

function UIRevengeRecord.RefreshRevengeRecordList()
    if this.revenge_history_list ~= nil and next(this.revenge_history_list) ~= nil then
        table.sort(this.revenge_history_list, function(a, b) 
            local a_dis_time = tonumber(tostring(a.record.createTime)) + this.rob_record_over_time - Config.serverTime
            local b_dis_time = tonumber(tostring(b.record.createTime)) + this.rob_record_over_time - Config.serverTime 
            if a_dis_time > 0 and b_dis_time > 0 then
                return a_dis_time > b_dis_time
            elseif a_dis_time > 0 and b_dis_time <= 0 then
                return true
            elseif a_dis_time <= 0 and b_dis_time > 0 then
                return false
            else
                return a_dis_time < b_dis_time
            end 
        end)
    end
    if #this.revenge_history_list > 0 then
        this.list_show:SetSelectedIndex(0)
    else
        this.list_show:SetSelectedIndex(1)
    end 
    this.list_revenge.numItems = #this.revenge_history_list 
end


-- <field class="long" name="id" explain="唯一id"></field>
-- <field class="long" name="playerId" explain="玩家id"></field>
-- <field class="String" name="name" explain="玩家名字"></field>
-- <field class="String" name="pic" explain="角色头像"></field>
-- <field class="int" name="picFrame" explain="头像框"></field>
-- <field class="int" name="lv" explain="等级"></field>
-- <field class="int" name="type" explain="类型 1被掠夺 2被复仇"></field>
-- <field class="com.game.battle.bean.BattleRecord" name="record" explain="战斗记录"></field>
function UIRevengeRecord.UpdateRevengeItemRender( index, obj )   

    if this.timer_list[index] ~= nil then
        utimer.remove(this.timer_list[index])
        this.timer_list[index] = nil
    end

    local item_info = this.revenge_history_list[index + 1] 

    -- item_info = {}
    -- item_info.type = 1
    -- item_info.pic = "1"
    -- item_info.picFrame = "2"
    -- item_info.items = {}
    -- item_info.name = "名字"
    -- item_info.record = {}
    -- item_info.record.createTime = "1622876690000"
    -- item_info.record.defender = {}
    -- item_info.record.attacker = {} 

    if item_info then
        local btn_head = obj:GetChild("Btn_Head")  
        btn_head:GetChild("head"):GetChild("HeadIcon").url =logicMgr.SkinManager.GetHeroIconBySkinId(item_info.pic)
        btn_head:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. item_info.picFrame 

        -- local btn_robitem = {}
        -- btn_robitem[1] = obj:GetChild("Btn_RobItem01")
        -- btn_robitem[2] = obj:GetChild("Btn_RobItem02")
        -- btn_robitem[3] = obj:GetChild("Btn_RobItem03")
        -- btn_robitem[1].visible = false
        -- btn_robitem[2].visible = false
        -- btn_robitem[3].visible = false
        -- local sub_items = item_info.items  
        -- local sub_index = 1
        -- for i = 1,  3 do 
        --     if sub_items[i] ~= nil then 
        --         this.showItemData(btn_robitem[sub_index], sub_items[i] )
        --         sub_index = sub_index+1
        --     end
        -- end
        
        local list_robitem = obj:GetChild("List_RobItem")
        list_robitem.itemRenderer = this.showItemData
        this.sub_items = item_info.items or {}
        local sub_item_count = #this.sub_items 
        list_robitem.numItems = sub_item_count
        if sub_item_count <= 3 then
            list_robitem.touchable = false
        else
            list_robitem.touchable = true
        end

        local txt_player_name = obj:GetChild("Text_PlayerName")
        txt_player_name.text = item_info.name or ""

        local txt_fight_time = obj:GetChild("Text_FightTime")
        local create_time = tonumber(tostring(item_info.record.createTime))
        txt_fight_time.text = getTimeStrType2(create_time)

        local btn_record = obj:GetChild("Btn_Record")
        btn_record.onClick:Clear()
        btn_record.onClick:Add(function() 
            local temp = item_info.record.defender
            item_info.record.defender = item_info.record.attacker
            item_info.record.attacker = temp 
            if item_info.record.win == 1 then
                item_info.record.win = 0
            else
                item_info.record.win = 1
            end
            showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.Plunder, item_info.record, nil, nil, 2)
        end) 

        local btn_revenge = obj:GetChild("Btn_Revenge") 
        btn_revenge.onClick:Clear() 
        btn_revenge.onClick:Add(function()
            this.onClickRevenge( item_info )
        end) 

        local revenge_controller = obj:GetController("Revenge")  
        local revenge_end_time = create_time + this.rob_record_over_time
        local dis_time = revenge_end_time - Config.serverTime
        if dis_time > 0 then 
            local txt_revenge_time = obj:GetChild("Text_RevengeTime")  
            dis_time = math.ceil(dis_time/1000)
            txt_revenge_time.text = string.format(getLanguage("RogueTips03"), timeToTimeFormat2(dis_time)) --"可回击"..timeToTimeFormat2(dis_time)
            revenge_controller:SetSelectedIndex(0)
            this.timer_list[index] = utimer.timeCall(function() 
                dis_time = dis_time -1 
                if txt_revenge_time then
                    txt_revenge_time.text = string.format(getLanguage("RogueTips03"), timeToTimeFormat2(dis_time)) --"可回击"..timeToTimeFormat2(dis_time)
                end
                if dis_time <= 0 then
                    revenge_controller:SetSelectedIndex(1)
                    utimer.remove(this.timer_list[index])
                    this.timer_list[index] = nil 
                end
            end, 1000, dis_time) 
        else
            revenge_controller:SetSelectedIndex(1)
        end  
    end
end

function UIRevengeRecord.showItemData( index, obj_p ) -- , data ) 
    local data = this.sub_items[index+1] 
    if data ~= nil then 
        local obj = obj_p:GetChild("n0")
        local img_Quality = obj:GetChild("quality") 
        local img_Frame = obj:GetChild("frame")
        local img_Icon = obj:GetChild("icon")
        local txt_num = obj:GetChild("num")
        local name = obj:GetChild("name")
        local cornerMark = obj:GetChild("cornerMark")
        local ctrlSuit = obj:GetController("suit")  
        local ctrlMirror = obj:GetController("heroMirror")
        local cornerMarkController = obj:GetController("cornerMark")
        if cornerMarkController then
            cornerMarkController.selectedIndex = 0
        end

        UIComponentInterface:SetItemAllById(img_Icon, img_Quality, img_Frame, data.itemModelId)
        local constData = ItemManager.getItemConstDatabyModelId(data.itemModelId)
        if constData and constData.itemType == EnumConst.ItemTypeEnum.Title then
            img_Icon.url = EnumConst.AtlasPath.ICONAtlas .. constData.icon 
        end
        if ctrlMirror then
            if constData and constData.icon and constData.itemType == EnumConst.ItemTypeEnum.Hero then
                img_Icon.url = EnumConst.AtlasPath.ICONAtlas .. constData.icon
                ctrlMirror.selectedIndex = 1
            else
                ctrlMirror.selectedIndex = 0
            end
        end
        if constData and constData.cornerMark ~= "" then
            if cornerMarkController then
                cornerMarkController.selectedIndex = 1
            end
            if cornerMark then
                cornerMark.url = EnumConst.AtlasPath.ICONAtlas .. constData.cornerMark;
            end
        end
        if ctrlSuit then
            if logicMgr.ItemManager.IsEquip(data.itemModelId) then
                local cfg = dataTable.getDataTableByStringId("t_equip",data.itemModelId)
                ctrlSuit.selectedIndex = cfg.f_EquipSuit 
            else
                ctrlSuit.selectedIndex = 0
            end
        end

        local num_value = tonumber(tostring(data.num))
        if txt_num then
            if data.num ~= nil and data.num ~= "" then
                if logicMgr.ItemManager.IsEquip(data.itemModelId) then
                    if  num_value == 1 then
                        txt_num.text = ""
                    else
                        txt_num.text = getNumString(num_value )
                    end
                else
                    txt_num.text = getNumString( num_value )
                end
            else
                txt_num.text = ""
            end
        end 
    end
end

-- 复仇
function UIRevengeRecord.ResRevengeMessage( msg ) 
    if this.cur_type == 2 then
        if msg and msg.info then  
            plunderHandler.atk_target_name = msg.info.name or ""
            local oppo_formation = {}   
            for k, v in pairs(msg.info.formations) do 
                if v and v.partnerModelId ~= 0 then 
                    local formation_item = {}
                    formation_item["partnerId"] = tostring(v.partnerId)
                    formation_item["partnerModelId"] = v.partnerModelId
                    formation_item["level"] = v.level
                    formation_item["star"] = v.star
                    formation_item["weaponLevel"] = 0
                    formation_item["icon"] = "" 
                    formation_item["state"] = 0 
                    formation_item["power"] = v.fightVal
                    oppo_formation[k] = formation_item 
                end
            end
            for i = 1, 6 do
                if oppo_formation[i] == nil then
                    local formation_item = {}
                    formation_item["partnerId"] = 0
                    formation_item["partnerModelId"] = 0
                    formation_item["level"] =0
                    formation_item["star"] = 0
                    formation_item["weaponLevel"] = 0
                    formation_item["icon"] = "" 
                    formation_item["state"] = 0 
                    formation_item["power"] = 0
                    oppo_formation[i] = formation_item
                end
            end  
            local param = {}
            param.playerId = 0
            param.power = 0
            param.type = EnumConst.FormationType.Plunder
            param.formation = plunderHandler.atk_formation or {} 
            param.oppo_formation = oppo_formation
            param.supSkillId = msg.info.skillId
            showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.Plunder, param, function(formations)
                local flag = true;
                if formations[1] ~= nil then
                    for i = 1, #formations[1] do
                        if formations[1][i] ~= nil and tonumber(tostring(formations[1][i])) > 0 then
                            flag = false;
                            break ;
                        end
                    end
                end
                if this.cur_revenge_end_time <= Config.serverTime then
                    UISysTips.AddMsg(getLanguage("ErrorCode_206"))
                    return
                end
                if flag then
                    UISysTips.AddMsg("需要上阵至少一名英雄")
                else  
                    plunderHandler.atk_formation = formations[1]
                    local data = {}
                    data.playerId = msg.info.playerId
                    data.formation = formations[1]
                    data.type = 2
                    data.historyId = this.historyId or 0
                    data.targetId = 0
                    plunderHandler.is_revenge_dot = true
                    plunderHandler.sendReqPlunderBattle( data ) --对战
                end 
                this.CloseSelf()
            end, function() 
            end)
        end 
    end
end

-- 点击复仇按钮
function UIRevengeRecord.onClickRevenge( item_info ) 
    plunderHandler.Track_clickRevenge(item_info.playerId) 
    if not isOpenUI(PanelNames.UIBattleTeam) then
        plunderHandler.is_revenge = true
        this.historyId = item_info.id 
        this.cur_revenge_end_time = tonumber(tostring(item_info.record.createTime)) + this.rob_record_over_time  
        plunderHandler.sendReqPlunderTargetInfo( item_info.playerId ) 
    end
end

---------------------------------------------------------------------------------------------------------------------
-- 掠夺记录

-- <field class="long" name="id" explain="唯一id"></field>
-- <field class="long" name="playerId" explain="玩家id"></field>
-- <field class="String" name="name" explain="玩家名字"></field>
-- <field class="String" name="pic" explain="角色头像"></field>
-- <field class="int" name="picFrame" explain="头像框"></field>
-- <field class="int" name="lv" explain="等级"></field>
-- <field class="int" name="type" explain="类型 1被掠夺 2被复仇"></field>
-- <field class="com.game.battle.bean.BattleRecord" name="record" explain="战斗记录"></field>
function UIRevengeRecord.UpdateRobItemRender( index, obj )   
    
    local item_info = this.rob_history_list[index + 1]  
    -- item_info = {}
    -- item_info.type = 1
    -- item_info.pic = "1"
    -- item_info.picFrame = "2"
    -- item_info.items = {}
    -- item_info.name = "名字"
    -- item_info.record = {}
    -- item_info.record.createTime = "1622876690000"
    -- item_info.record.defender = {}
    -- item_info.record.attacker = {} 

    if item_info then
        local btn_head = obj:GetChild("Btn_Head")
        btn_head.onClick:Clear()
        btn_head:GetChild("head"):GetChild("HeadIcon").url = logicMgr.SkinManager.GetHeroIconBySkinId(item_info.pic)
        btn_head:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. item_info.picFrame 

        -- local btn_robitem = {}
        -- btn_robitem[1] = obj:GetChild("Btn_RobItem01")
        -- btn_robitem[2] = obj:GetChild("Btn_RobItem02")
        -- btn_robitem[3] = obj:GetChild("Btn_RobItem03")
        -- btn_robitem[1].visible = false
        -- btn_robitem[2].visible = false
        -- btn_robitem[3].visible = false
        -- local sub_items = item_info.items  
        -- local sub_index = 1
        -- for i = 1,  3 do 
        --     if sub_items[i] ~= nil then 
        --         this.showItemData(btn_robitem[sub_index], sub_items[i] )
        --         sub_index = sub_index+1
        --     end
        -- end
        local list_robitem = obj:GetChild("List_RobItem")
        list_robitem.itemRenderer = this.showItemData
        this.sub_items = item_info.items or {}
        local sub_item_count = #this.sub_items
        list_robitem.numItems = sub_item_count
        if sub_item_count <= 3 then
            list_robitem.touchable = false
        else
            list_robitem.touchable = true
        end

        local txt_player_name = obj:GetChild("Text_PlayerName")
        txt_player_name.text = item_info.name or ""

        local txt_fight_time = obj:GetChild("Text_FightTime")
        local create_time = tonumber(tostring(item_info.record.createTime))
        txt_fight_time.text = getTimeStrType2(create_time)

        local btn_record = obj:GetChild("Btn_Record")
        btn_record.onClick:Clear()
        btn_record.onClick:Add(function()
            showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.Plunder, item_info.record, nil, nil, 2)
        end) 
 
        local btn_receive = obj:GetChild("Btn_Get") 
        btn_receive.onClick:Clear() 
        btn_receive.onClick:Add(function()
            this.item_rewards = sub_items
            this.onClickReceiveReward( item_info )
            plunderHandler.Track_plunderClickReward(item_info)
            plunderHandler.Track_plunderReceiveReward(item_info)
        end)  

        local rob_controller = obj:GetController("Rob")
        utimer.remove(this.timer_list[index])
        this.timer_list[index] = nil
        if item_info.type == 3 then -- 被掠夺
            rob_controller:SetSelectedIndex(1)
            local revenge_end_time = create_time + this.rob_record_over_time 
            local dis_time = revenge_end_time - Config.serverTime
            if dis_time > 0 then 
                rob_controller:SetSelectedIndex(1)
                dis_time = math.ceil(dis_time/1000)
                local txt_wait_time = obj:GetChild("Text_GetTime") 
                txt_wait_time.text = string.format(getLanguage("RogueTips04"), timeToTimeFormat2(dis_time)) --"等待对手反击\n"..timeToTimeFormat(dis_time)
                this.timer_list[index] = utimer.timeCall(function() 
                    dis_time = math.ceil((revenge_end_time - Config.serverTime) / 1000)
                    if txt_wait_time then 
                        txt_wait_time.text = string.format(getLanguage("RogueTips04"), timeToTimeFormat2(dis_time)) --"等待对手反击\n"..timeToTimeFormat(dis_time)
                    end
                    if dis_time <= 0 then
                        rob_controller:SetSelectedIndex(0)
                        utimer.remove(this.timer_list[index])
                        this.timer_list[index] = nil
                        this.UpdateRedDot() 
                        this.RefreshRobRecordList()
                    end
                end, 1000, dis_time) 
            else 
                rob_controller:SetSelectedIndex(0)
            end
        -- elseif item_info.type == 2 then -- 被复仇
        --     rob_controller:SetSelectedIndex(1)
        else
            rob_controller:SetSelectedIndex(2)
        end 
        -- if item_info.type == 5 then -- 被复仇
        --     rob_controller:SetSelectedIndex(2)
        -- else 
        -- end
    end
end

function UIRevengeRecord.UpdateRedDot() 
    -- FireEvent(Config.EventType.Fresh_WorldMapReceiveRobReward)
    -- FireEvent(Config.EventType.Fresh_WorldMapRevengeList)
    FireEvent(Config.EventType.Fresh_WorldMapReceiveRobReward)
end

function UIRevengeRecord.onClickReceiveReward( item_info )   
    plunderHandler.sendReqGetPlunderRewardMessage( item_info.id )  
end

function UIRevengeRecord.ResPlunderRobReward( msg )  
    plunderHandler.sendReqRobList( 1 ) -- 掠夺记录
    if this.item_rewards ~= nil and next(this.item_rewards) ~= nil then
        showUI(PanelNames.UICommonItemGet, nil, nil, 3, this.item_rewards)
        this.item_rewards = nil
    end
end



--------------------------------------------------------------------------------------------------

function UIRevengeRecord.ClickRobListCallback() 
    this.cur_type = 1
    this.page_controller:SetSelectedIndex(0)
    plunderHandler.sendReqRobList( 1 ) -- 掠夺记录 
end
function UIRevengeRecord.ClickRevengeListCallback() 
    plunderHandler.SetRevengeListRedDotData( false ) 
    this.cur_type = 2 
    this.page_controller:SetSelectedIndex(1)
    plunderHandler.sendReqRobList( 2 ) --复仇记录  
end

function UIRevengeRecord.addEvent() 
    this.btn_back.onClick:Add(this.CloseSelf) 
    this.btn_bg_back.onClick:Add(this.CloseSelf)
    this.btn_rob_list.onClick:Add(this.ClickRobListCallback)
    this.btn_revenge_list.onClick:Add(this.ClickRevengeListCallback)
 
    UIRedDots.addViewListen(PanelNames.UIRevengeRecord, "btn_rob_list_tab", this.btn_rob_list, Config.RedDotsType.WorldMapReceiveRobReward)  
    UIRedDots.addViewListen(PanelNames.UIRevengeRecord, "btn_revenge_list_tab", this.btn_revenge_list, Config.RedDotsType.WorldMapRevengeTabList)
end

function UIRevengeRecord.removeEvent() 
    this.btn_back.onClick:Clear() 
    this.btn_bg_back.onClick:Clear()
    this.btn_rob_list.onClick:Clear()
    this.btn_revenge_list.onClick:Clear()
    UIRedDots.removeViewEvent(PanelNames.UIRevengeRecord)
end

function UIRevengeRecord.CloseSelf() 
    DestoryUI(PanelNames.UIRevengeRecord)
end

function UIRevengeRecord.ClearTimer()
    for k, v in pairs(this.timer_list) do
        if this.timer_list[k] ~= nil then
            utimer.remove(this.timer_list[k])
            this.timer_list[k] = nil
        end
    end
end
 
function UIRevengeRecord.OnDestroy() 
    this.ClearTimer()
    this.removeEvent()
    this.hasInit = nil
    this.root = nil
    this.list_show = nil
    plunderHandler.is_revenge = nil
end


return UIRevengeRecord
